package com.ruoyi.hbs.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.exception.ServiceException;

import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.stream.Collectors;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.hbs.mapper.SalesInventoryRecordsMapper;
import com.ruoyi.hbs.domain.SalesInventoryRecords;
import com.ruoyi.hbs.service.SalesInventoryRecordsService;
import org.springframework.transaction.annotation.Transactional;

@Service
public class SalesInventoryRecordsServiceImpl extends ServiceImpl<SalesInventoryRecordsMapper, SalesInventoryRecords> implements SalesInventoryRecordsService{


    @Autowired
    private SalesInventoryRecordsMapper salesInventoryRecordsMapper;

    /**
     * 查询码上健康-药品销售与库存
     *
     * @param id 码上健康-药品销售与库存主键
     * @return 码上健康-药品销售与库存
     */
    @Override
    public SalesInventoryRecords selectSalesInventoryRecordsById(Long id)
    {
        return salesInventoryRecordsMapper.selectSalesInventoryRecordsById(id);
    }

    /**
     * 查询码上健康-药品销售与库存列表
     *
     * @param salesInventoryRecords 码上健康-药品销售与库存
     * @return 码上健康-药品销售与库存
     */
    @Override
    public List<SalesInventoryRecords> selectSalesInventoryRecordsList(SalesInventoryRecords salesInventoryRecords)
    {
        return salesInventoryRecordsMapper.selectSalesInventoryRecordsList(salesInventoryRecords);
    }

    /**
     * 新增码上健康-药品销售与库存
     *
     * @param salesInventoryRecords 码上健康-药品销售与库存
     * @return 结果
     */
    @Override
    public int insertSalesInventoryRecords(SalesInventoryRecords salesInventoryRecords)
    {
        return salesInventoryRecordsMapper.insertSalesInventoryRecords(salesInventoryRecords);
    }

    /**
     * 修改码上健康-药品销售与库存
     *
     * @param salesInventoryRecords 码上健康-药品销售与库存
     * @return 结果
     */
    @Override
    public int updateSalesInventoryRecords(SalesInventoryRecords salesInventoryRecords)
    {
        return salesInventoryRecordsMapper.updateSalesInventoryRecords(salesInventoryRecords);
    }

    /**
     * 批量删除码上健康-药品销售与库存
     *
     * @param ids 需要删除的码上健康-药品销售与库存主键
     * @return 结果
     */
    @Override
    public int deleteSalesInventoryRecordsByIds(Long[] ids)
    {
        return salesInventoryRecordsMapper.deleteSalesInventoryRecordsByIds(ids);
    }

    /**
     * 删除码上健康-药品销售与库存信息
     *
     * @param id 码上健康-药品销售与库存主键
     * @return 结果
     */
    @Override
    public int deleteSalesInventoryRecordsById(Long id)
    {
        return salesInventoryRecordsMapper.deleteSalesInventoryRecordsById(id);
    }
    /**
     * 导入数据
     *
     * @param salesInventoryRecordsList 销售库存管理列表
     * @param operName 操作用户
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public  String importSalesInventoryRecords(List<SalesInventoryRecords> salesInventoryRecordsList, String operName){
        if (org.springframework.util.CollectionUtils.isEmpty(salesInventoryRecordsList)) {
            throw new ServiceException("导入数据不能为空！");
        }

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        try {
            // 提取所有唯一标识
            List<String> billIdDetailIds = salesInventoryRecordsList.stream()
                    .map(SalesInventoryRecords::getBillIdDetailId)
                    .filter(org.springframework.util.StringUtils::hasText)
                    .distinct()
                    .collect(Collectors.toList());

            // 批量查询已存在的记录
            Set<String> existingBillIdDetailIds;
            if (!billIdDetailIds.isEmpty()) {
                List<SalesInventoryRecords> existingRecords = salesInventoryRecordsMapper.selectList(
                        new LambdaQueryWrapper<SalesInventoryRecords>()
                                .in(SalesInventoryRecords::getBillIdDetailId, billIdDetailIds)
                                .select(SalesInventoryRecords::getBillIdDetailId)
                );

                existingBillIdDetailIds = existingRecords.stream()
                        .map(SalesInventoryRecords::getBillIdDetailId)
                        .collect(Collectors.toSet());
            } else {
                existingBillIdDetailIds = new HashSet<>();
            }

            // 筛选出需要插入的数据
            List<SalesInventoryRecords> toInsertList = salesInventoryRecordsList.stream()
                    .filter(record -> record.getBillIdDetailId() != null &&
                            !existingBillIdDetailIds.contains(record.getBillIdDetailId()))
                    .collect(Collectors.toList());

            // 批量插入
            if (!toInsertList.isEmpty()) {
                boolean result = this.saveBatch(toInsertList, 1000);
                if (result) {
                    successNum = toInsertList.size();
                    successMsg.append("成功导入 ").append(successNum).append(" 条记录");
                } else {
                    failureNum = toInsertList.size();
                    failureMsg.append("导入失败 ").append(failureNum).append(" 条记录");
                }
            } else {
                successMsg.append("所有数据已存在，无需导入");
            }

        } catch (Exception e) {
            log.error("导入销售库存记录时发生异常", e);
            failureNum = salesInventoryRecordsList.size();
            failureMsg.append("导入过程中发生异常：").append(e.getMessage());
        }

        // 处理结果
        if (failureNum > 0) {
            failureMsg.insert(0, "导入完成，其中成功 " + successNum + " 条，失败 " + failureNum + " 条。");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，详情如下：");
        }

        return successMsg.toString();
    }
}
